# -*- coding:utf-8 -*-
import logging
import logging.handlers
import os,sys
sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), os.pardir))
from supeanut_config import *

# *** author: peanut
# *** date: 2016-12-07
# 1.在根目录下打日志
# 2.设定日志大小上限
# 3.屏幕显示为INFO级别
#   写入文件为WARNING,ERROR级别
class mylog:
	# INPUT: str or None
	def __init__(self, log_module, MP_num):
		# config param
		# --MB
		logsize = LOG_FILE_MAXSIZE*1024*1024
		# --MultiProcess_number
		if MP_num is None:
			MP_num = ''
		# --logger name
		if log_module is None or log_module == '':
			log_module = 'root'
		if MP_num <> '':
			log_module += ('_' + MP_num)
		# log file path
		exec_filename = sys.argv[0].split('/')[-1].split('.')[0]
		log_path = LOG_BASE_PATH + exec_filename + r'.log'
		if not os.path.exists(LOG_BASE_PATH):
			os.mkdir(LOG_BASE_PATH)
		# init logger
		self.logger = logging.getLogger(log_module)
		self.logger.setLevel(logging.DEBUG)
		formatter = logging.Formatter('[%(asctime)s][%(name)s][%(levelname)s] %(message)s', '%Y-%m-%d %H:%M:%S')
		# file handler
		fh = logging.handlers.RotatingFileHandler(log_path, maxBytes=logsize, backupCount=LOG_FILE_MAXNUM)
		# --日期rotate形式
		# --TimedRotatingFileHandler
		fh.setLevel(LOG_FILE_LEVEL)
		fh.setFormatter(formatter)
		# stream handler
		sh = logging.StreamHandler(stream=sys.stdout)
		sh.setLevel(LOG_SHOW_LEVEL)
		sh.setFormatter(formatter)
		# load handler
		if self.logger.handlers == []:
			self.logger.addHandler(fh)
			self.logger.addHandler(sh)
	
	def info(self, msg):
		self.logger.info(msg)
	
	def warning(self, msg):
		self.logger.warning(msg)

	def error(self, msg):
		self.logger.error(msg)

	def exception(self, msg):
		self.logger.exception(msg)
